package com.dayuanit.service.impl;

import com.dayuanit.controller.request.LoginParam;
import com.dayuanit.controller.request.RegisterApplyUserParam;
import com.dayuanit.dao.ApplyUserDao;
import com.dayuanit.entity.ApplyUser;
import com.dayuanit.exception.BusinessEnum;
import com.dayuanit.exception.BusinessException;
import com.dayuanit.service.ApplyUserService;
import com.dayuanit.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApplyUserServiceImpl implements ApplyUserService {

    @Autowired(required = false)
    private ApplyUserDao applyUserDao;

    @Override
    public void register(RegisterApplyUserParam param) {
        //查询该手机号是不是已经被注册过
        ApplyUser checkUser = applyUserDao.findApplyUserByPhone(param.getPhone());
        if(checkUser != null) {
            throw new BusinessException(BusinessEnum.PHONE_IS_REGISTERED);
        }
        //创建新的对象插入到表里
        ApplyUser applyUser = new ApplyUser();
        applyUser.setApplyUserName(param.getApplyUserName());
        applyUser.setPhone(param.getPhone());
        applyUser.setLastUpdateTime(new Date());
        applyUser.setAddTime(new Date());
        applyUser.setIsDelete(0);

        //密码进行加密处理
        applyUser.setPassword(Md5Util.encoderByMd5(param.getPassword()));

        int i = applyUserDao.insert(applyUser);
        if(i != 1) {
            throw new RuntimeException("db error");
        }


    }



    @Override
    public ApplyUser login(LoginParam loginparam) {
        //根据手机号去查询前台用户信息
        ApplyUser applyUser = applyUserDao.findApplyUserByPhone(loginparam.getPhone());
        if(applyUser == null) {
            throw new BusinessException(BusinessEnum.PHONE_OR_PASSWORD_ERROR);
        }
        //如果密码错误，则返回手机号或者密码错误
        String pwd = Md5Util.encoderByMd5(loginparam.getPassword());
        if(!applyUser.getPassword().equals(pwd)) {
            throw new BusinessException(BusinessEnum.PHONE_OR_PASSWORD_ERROR);
        }
        return applyUser;
    }
}
